<template>
  <!-- :rules="rules" -->
  <el-drawer
    v-model="drawerVisible"
    :destroy-on-close="true"
    size="450px"
    :title="`${drawerProps.title}${t('accessControl.userManagement.user')}`"
  >
    <el-form
      ref="ruleFormRef"
      label-width="200px"
      label-suffix=" :"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <!-- <el-form-item label="用户头像" prop="avatar">
        <UploadImg v-model:image-url="drawerProps.row!.avatar" width="135px" height="135px" :file-size="3">
          <template #empty>
            <el-icon><Avatar /></el-icon>
            <span>请上传头像</span>
          </template>
          <template #tip> 头像大小不能超过 3M </template>
        </UploadImg>
      </el-form-item>
      <el-form-item label="用户照片" prop="photo">
        <UploadImgs v-model:file-list="drawerProps.row!.photo" height="140px" width="140px" border-radius="50%">
          <template #empty>
            <el-icon><Picture /></el-icon>
            <span>请上传照片</span>
          </template>
          <template #tip> 照片大小不能超过 5M </template>
        </UploadImgs>
      </el-form-item> -->
      <el-form-item :label="t('accessControl.userManagement.loginName')" prop="loginName">
        <el-input
          v-model="drawerProps.row!.loginName"
          :placeholder="t('accessControl.userManagement.loginName')"
          clearable
          :disabled="drawerProps.isadd"
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="t('accessControl.userManagement.password')"
        v-if="drawerProps.title == t('accessControl.userManagement.add')"
      >
        <el-input
          v-model="pwd"
          :placeholder="t('accessControl.userManagement.password')"
          clearable
          type="password"
          :disabled="drawerProps.isadd"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="t('accessControl.userManagement.confirmPassword')"
        v-if="drawerProps.title == t('accessControl.userManagement.add')"
      >
        <el-input
          v-model="rpwd"
          :placeholder="t('accessControl.userManagement.confirmPassword')"
          clearable
          type="password"
          :disabled="drawerProps.isadd"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item :label="t('accessControl.userManagement.firstName')" prop="firstName">
        <el-input
          v-model="drawerProps.row!.firstName"
          :placeholder="t('accessControl.userManagement.pleaseEnterFirstName')"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item :label="t('accessControl.userManagement.lastName')" prop="lastName">
        <el-input
          v-model="drawerProps.row!.lastName"
          :placeholder="t('accessControl.userManagement.pleaseEnterLastName')"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item :label="t('accessControl.userManagement.fullName')" prop="fullName">
        <el-input
          v-model="drawerProps.row!.fullName"
          :placeholder="t('accessControl.userManagement.pleaseEnterFullName')"
          clearable
        ></el-input>
      </el-form-item>

      <el-form-item label="所属机构" prop="belongsGroupStr">
        <el-tree-select
          style="width: 180px"
          v-model="orgSelect"
          :data="treeFilterData"
          :render-after-expand="false"
          show-checkbox
          check-strictly
          check-on-click-node
        />
      </el-form-item>
      <el-form-item :label="t('accessControl.userManagement.technicalGroup')" prop="belongsGroupStr">
        <el-tree-select
          style="width: 180px"
          v-model="belongsGroupSelect"
          :data="treeFilterData"
          multiple
          :render-after-expand="false"
          show-checkbox
          check-strictly
          check-on-click-node
        />

        <!-- <el-row>
          <el-col :span="12">
            <el-cascader
              v-model="belongsGroupSelect"
              :options="treeFilterData"
              :show-all-levels="false"
              :placeholder="t('accessControl.userManagement.technicalGroup')"
              @update:model-value="getVal"
              :props="props1"
            />
          </el-col>
          <el-col :span="12">
            <el-input v-model="drawerProps.row!.orgName"></el-input>
          </el-col>
        </el-row>
        <el-input v-model="drawerProps.row!.belongsGroupStr" clearable style="display: none"></el-input> -->
        <!-- <el-input
          v-model="drawerProps.row!.belongsGroupStr"
          placeholder="所属技术组"
          v-if="drawerProps.title == '查看'"
          clearable
        ></el-input> -->
      </el-form-item>
      <!-- <el-form-item label="所属技术组" prop="belongsGroupStr">
        <el-input v-model="drawerProps.row!.belongsGroupStr" placeholder="所属技术组" clearable></el-input>
      </el-form-item> -->
      <!-- <el-form-item label="用户角色" prop="roles">
        <el-input v-model="drawerProps.row!.roles" placeholder="用户角色" clearable></el-input>
      </el-form-item> -->
      <el-form-item :label="t('accessControl.userManagement.roles')" prop="roles">
        <el-select multiple v-model="selectRolesData" :placeholder="t('accessControl.userManagement.roles')" clearable>
          <el-option v-for="item in rolesData" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('accessControl.userManagement.mobile')" prop="moblie">
        <el-input v-model="drawerProps.row!.moblie" :placeholder="t('accessControl.userManagement.mobile')" clearable></el-input>
      </el-form-item>
      <el-form-item :label="t('accessControl.userManagement.email')" prop="email">
        <el-input
          v-model="drawerProps.row!.email"
          :placeholder="t('accessControl.userManagement.pleaseEnterEmail')"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item :label="t('accessControl.userManagement.status')" prop="userState">
        <!-- <el-input v-model="userState" placeholder="状态" clearable></el-input> -->
        <el-select v-model="drawerProps.row!.userState" :placeholder="t('accessControl.userManagement.status')" clearable>
          <el-option v-for="item in state" :key="item.label" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('accessControl.userManagement.holidayStatus')" prop="userState">
        <!-- <el-input v-model="userState" placeholder="状态" clearable></el-input> -->
        <el-select
          v-model="drawerProps.row!.holidayStatus"
          :placeholder="t('accessControl.userManagement.holidayStatus')"
          clearable
        >
          <el-option v-for="item in holiday" :key="item.label" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('accessControl.userManagement.engineerCost')" prop="userCost">
        <el-input
          v-model="drawerProps.row!.userCost"
          :placeholder="t('accessControl.userManagement.pleaseEnterEngineerCost')"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">{{ t("common.cancel") }}</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">{{ t("common.confirm") }}</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, onMounted, reactive } from "vue";
// reactive computed
// import { genderType } from "@/utils/dict";
import { ElMessage, FormInstance } from "element-plus";
import { User } from "@/api/interface";
// import UploadImg from "@/components/Upload/Img.vue";
// import UploadImgs from "@/components/Upload/Imgs.vue";
import { getRoleList, getUserDepartment } from "@/api/modules/user";
import { useI18n } from "vue-i18n";
// const rules = reactive({
//   avatar: [{ required: true, message: "请上传用户头像" }],
//   photo: [{ required: true, message: "请上传用户照片" }],
//   username: [{ required: true, message: "请填写用户姓名" }],
//   gender: [{ required: true, message: "请选择性别" }],
//   idCard: [{ required: true, message: "请填写身份证号" }],
//   email: [{ required: true, message: "请填写邮箱" }],
//   address: [{ required: true, message: "请填写居住地址" }]
// });
//
const { t } = useI18n();

// const props1 = {
//   checkStrictly: true,
//   label: "data",
//   value: "data",
//   multiple: true
// };

const pwd = ref("");
const rpwd = ref("");
//获取所属部门
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const data = await getUserDepartment();
  console.log(data);
  if (data) {
    treeFilterData.value = data;

    traverseTree(treeFilterData.value[0], node => {
      if (node.attr.orgNo.toString() == "1") {
        node["disabled"] = true;
      }
      node.label = node.attr.orgName;
      node.value = node.attr.orgNo;
    });

    console.log(treeFilterData.value);
  }
};
onMounted(() => {
  getTreeFilter();
  getRole();
});
// const stateVal = ref("");
const state = [
  {
    value: true,
    label: t("accessControl.userManagement.enabled")
  },
  {
    value: false,
    label: t("accessControl.userManagement.disabled")
  }
];
const holiday = [
  {
    value: false,
    label: t("accessControl.userManagement.onDuty")
  },
  {
    value: true,
    label: t("accessControl.userManagement.onHoliday")
  }
];
interface Role {
  roleId: string;
  roleName: string;
}

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<User.ResUserList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  val?: any[] | undefined;
  isadd: boolean;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  isadd: false,
  title: "",
  val: [],
  row: {}
});

const selectRolesData = ref<Role[]>([]);
const rolesData = ref<Role[]>([]);
// const selectedRole = ref(null);
//获取用户角色
const getRole = async () => {
  const data = await getRoleList();
  rolesData.value = data.data as Role[];
};
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  selectRolesData.value = [];
  belongsGroupSelect.value = [];

  drawerProps.value = params;
  drawerVisible.value = true;
  traverseTree(treeFilterData.value[0], node => {
    // console.log(node.attr.orgName == drawerProps.value.row.orgName);
    if (node.attr.orgName == drawerProps.value.row.orgName) {
      // console.log("node.attr.orgName==drawerProps.value.row.orgName");
      orgSelect.value = node.attr.orgNo;
      // drawerProps.value.row.belongsGroupStr = node.attr.orgName;

      // console.log(drawerProps.value.row.belongsGroupStr);
    }

    if (drawerProps.value.row.belongsGroupStr != undefined && drawerProps.value.row.belongsGroupStr != "") {
      let groupArr = drawerProps.value.row.belongsGroupStr.split(",");
      for (let j = 0; j < groupArr.length; j++) {
        if (node.attr.orgName == groupArr[j]) {
          belongsGroupSelect.value.push(node.attr.orgNo as any);
        }
      }
    }
  });
  if (drawerProps.value.row!.roles != undefined && drawerProps.value.row!.roles != "") {
    for (let i = 0; i < rolesData.value.length; i++) {
      let arr = drawerProps.value.row!.roles.split(",");
      for (let j = 0; j < arr.length; j++) {
        if (rolesData.value[i]["roleName"] == arr[j]) {
          selectRolesData.value.push(rolesData.value[i]["roleId"] as any);
        }
      }
    }
  }
};
const belongsGroupSelect = ref<any>([]);

const orgSelect = ref<any>([]);

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    console.log(drawerProps.value.val);
    try {
      let roleIdsStr = "";
      for (let i = 0; i < selectRolesData.value.length; i++) {
        if (roleIdsStr == "") {
          roleIdsStr = "?userDto.roleIds=" + selectRolesData.value[i];
        } else {
          roleIdsStr = roleIdsStr + "&userDto.roleIds=" + selectRolesData.value[i];
        }
      }

      let groupIdsStr = "";
      for (let i = 0; i < belongsGroupSelect.value.length; i++) {
        if (groupIdsStr == "") {
          groupIdsStr = "&userDto.belongsGroupIds=" + belongsGroupSelect.value[i];
        } else {
          groupIdsStr = groupIdsStr + "&userDto.belongsGroupIds=" + belongsGroupSelect.value[i];
        }
      }

      if (selectRolesData.value.length <= 0) {
        ElMessage.error(t("accessControl.userManagement.pleaseSelectRole"));
        return;
      }
      if (belongsGroupSelect.value.length <= 0) {
        ElMessage.error("请选择技术组");
        return;
      }
      const userInfo = reactive({
        "userDto.userId": drawerProps.value.row.userId,
        "userDto.companyNo": 1,
        "userDto.loginName": drawerProps.value.row.loginName,
        "userDto.firstName": drawerProps.value.row.firstName,
        "userDto.lastName": drawerProps.value.row.lastName,
        "userDto.belongsGroupIdsStr": groupIdsStr,
        // drawerProps.value.val === undefined ? "" : drawerProps.value.val[drawerProps.value.val.length - 1],
        "userDto.orgNo": orgSelect.value,
        // drawerProps.value.val === undefined ? "" : drawerProps.value.val[drawerProps.value.val.length - 1],
        "userDto.userState": drawerProps.value.row.userState == undefined ? true : drawerProps.value.row.userState,
        "userDto.holidayStatus": drawerProps.value.row.holidayStatus,
        "userDto.roleIdsStr": roleIdsStr,
        orgName: drawerProps.value.row.orgName,
        "userDto.email": drawerProps.value.row.email,
        "userDto.moblie": drawerProps.value.row.moblie,
        "userDto.phone": drawerProps.value.row.phone,
        "userDto.userCost": drawerProps.value.row!.userCost,
        "userDto.password": pwd,
        rpassword: rpwd
      });
      if (drawerProps.value.title == t("accessControl.userManagement.add")) {
        if (pwd.value !== rpwd.value) {
          ElMessage.error(t("accessControl.userManagement.passwordsDoNotMatch"));
          return;
        }
      }
      await drawerProps.value.api!(userInfo);
      ElMessage.success({ message: `${drawerProps.value.title}${t("accessControl.userManagement.user")}${t("common.success")}` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
interface Tree {
  label: string;
  children?: Tree[];
  attr: any;
}
interface TreeNode {
  value: any;
  lable: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
  data: any;
  label: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}
defineExpose({
  acceptParams
});
</script>
